import { EyeOutlined } from "@ant-design/icons";
import { ColorPicker, Form, Select } from "antd";
import { lab } from "color";
import type React from "react";
import { useEffect, useState } from "react";

interface ColorPickerFormItemProps {
	label: string;
	name: string;
	initialValue?: string;
	rules?: any[];
}

const ColorPickerFormItem: React.FC<ColorPickerFormItemProps> = ({
	label,
	name,
	initialValue = "#f50", // 默认初始化颜色
	rules = [],
}) => {
	const [isColorPickerVisible, setColorPickerVisible] = useState(false);
	const [selectedColor, setSelectedColor] = useState(initialValue);

	// 初始化颜色选项
	const colors = [
		{ label: "红色", value: "#D0362B" },
		{ label: "橙色", value: "#f50" },
		{ label: "天蓝", value: "#2db7f5" },
		{ label: "绿色", value: "#87d068" },
		{ label: "蓝色", value: "#108ee9" },
		{ label: "黄色", value: "#F7D14E" },
		{ label: "灰色", value: "#BFE0E3" },
	];

	// 选择颜色
	const handleSelectColor = (value: string) => {
		setSelectedColor(value);
		setColorPickerVisible(false);
	};

	// 当组件初始化时，确保表单和 ColorPicker 初始值一致
	useEffect(() => {
		setSelectedColor(initialValue || "#f50");
	}, [initialValue]);

	return (
		<Form.Item label={label} name={name} rules={rules}>
			<Select
				value={selectedColor} // 显示选中的颜色
				placeholder="选择颜色"
				suffixIcon={<EyeOutlined onClick={() => setColorPickerVisible(!isColorPickerVisible)} />}
				onChange={handleSelectColor}
				dropdownRender={(menu) => (
					<>
						{menu}
						{/* 显示颜色选择器 */}
						{isColorPickerVisible && <ColorPicker value={selectedColor} onChange={handleSelectColor} />}
					</>
				)}
			>
				{colors.map((color) => (
					<Select.Option key={color.value} value={color.value} label={color.label}>
						<div
							style={{
								display: "flex",
								alignItems: "center",
							}}
						>
							{/* 颜色块 */}
							<div
								style={{
									width: 20,
									height: 20,
									backgroundColor: color.value,
									marginRight: 10,
									borderRadius: "50%",
								}}
							/>
							{color.label}
						</div>
					</Select.Option>
				))}
			</Select>
		</Form.Item>
	);
};

export default ColorPickerFormItem;
